package cn.lena.idle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Toast;

import java.util.List;

import cn.lena.idle.dao.CatagoryDbHelper;
import cn.lena.idle.dao.GoodsDbHelper;
import cn.lena.idle.pojo.Catagory;
import cn.lena.idle.pojo.DTO.CurrentGoods;
import cn.lena.idle.pojo.DTO.Version;
import cn.lena.idle.pojo.Goods;
import cn.lena.idle.util.PhotoUtils;

/**
 * @author lena
 * @date 2021/6/12
 */
public class GoodsUpdateActivity extends AppCompatActivity {

    private Goods goods;
    private ImageButton photo;
    private ImageView back;
    private Button update;
    private EditText title;
    private EditText describe;
    private EditText catagory;
    private EditText price;
    private EditText address;
    private List<Catagory> catagories;
    private PopupMenu pm;
    private Integer cid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_update);

        goods= CurrentGoods.SELECT;
        cid=goods.getCatagoryId();
        photo=(ImageButton)findViewById(R.id.detail_photo);
        update=(Button) findViewById(R.id.update_button);
        title=(EditText)findViewById(R.id.detail_title);
        describe=(EditText)findViewById(R.id.detail_describe);
        catagory=(EditText)findViewById(R.id.detail_catagory);
        price=(EditText)findViewById(R.id.detail_price);
        address=(EditText)findViewById(R.id.detail_address);
        back=(ImageView)findViewById(R.id.returnbefore1);

        // 初始化输入框的值
        photo.setImageBitmap(BitmapFactory.decodeByteArray(goods.getPicture(),0,goods.getPicture().length));
        title.setText(goods.getGoodsName());
        describe.setText(goods.getDescribe());
        catagory.setText(getCatagorynameById(goods.getCatagoryId()));
        price.setText(goods.getPrice());
        address.setText(goods.getAddress());

        // 初始化：是否具有修改功能
        initUpdate();

        // 单击返回按钮
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(GoodsUpdateActivity.this,MyGoodsActivity.class);
                startActivity(intent);
            }
        });

        // 单击图片按钮时，能够在相册中选择图片
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,1);
            }
        });

    }

    /**
     * 判断当前登录用户是否就是发布商品的用户：是-允许修改，不是-隐藏修改按钮。
     */
    private void initUpdate(){
       // if(goods.getUserId() == LoginUser.CURRENT_USER.getId()){

        // 初始化菜单项 t
        initMenu();
        // 选择分类后添加下拉菜单项 t
        catagory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示菜单项
                pm.show();
            }
        });
        // 修改按钮：更新数据库的值
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                update();
            }
        });

        // 设置不可点
/*        photo.setEnabled(false);
        title.setKeyListener(null);
        describe.setKeyListener(null);
        catagory.setKeyListener(null);
        price.setKeyListener(null);
        address.setKeyListener(null);
        update.setVisibility(View.INVISIBLE);*/
    }

    /**
     * 选择图片后触发事件 t
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1) {
            //从相册返回的数据
            if (data != null) {
                //得到图片的全路径
                Uri uri = data.getData();
                photo.setImageURI(uri);
            }
        }
    }

    /**
     * 更新商品值
     */
    private void update(){

        // 更新值
        goods.setPicture(PhotoUtils.ImageButtonToByte(photo));
        goods.setGoodsName(title.getText().toString().trim());
        goods.setDescribe(describe.getText().toString().trim());
        goods.setCatagoryId(cid);
        goods.setPrice(price.getText().toString().trim());
        goods.setAddress(address.getText().toString().trim());

        // 数据库操作
        GoodsDbHelper goods_db=new GoodsDbHelper(getApplicationContext(),GoodsDbHelper.DB_NAME,null,Version.GOODS);
        int result = goods_db.updateGoods(goods);
        if(result == 1){
            Toast.makeText(this,"更新成功！",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(this,"更新失败！",Toast.LENGTH_LONG).show();
        }

    }

    /**
     * 根据分类id查询分类名称
     */
    private String getCatagorynameById(Integer id){
        CatagoryDbHelper catagory_db=new CatagoryDbHelper(getApplicationContext(), CatagoryDbHelper.DB_NAME,null,Version.CATAGORY);
        return catagory_db.getById(id);
    }


    /**
     * 初始化菜单项 t
     */
    private void initMenu(){

        pm=new PopupMenu(GoodsUpdateActivity.this,catagory);
        Menu menu=pm.getMenu();
        pm.getMenuInflater().inflate(R.menu.catagory,menu);

        // 查询所有分类
        findAll();

        // 将分类全部添加到菜单项中
        for(Catagory c:catagories){
            // 1-组别、2-菜单项id、3-菜单项顺序、4-菜单项内容
            menu.add(0,c.getId(),0,c.getName());
        }

        // 添加单击数据项事件
        pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                catagory.setText(item.getTitle());
                cid=item.getItemId();
                return true;
            }
        });

    }


    /**
     * 查询所有分类 t
     */
    private void findAll(){
        CatagoryDbHelper catagory_db=new CatagoryDbHelper(getApplicationContext(),CatagoryDbHelper.DB_NAME,null, Version.CATAGORY);
        catagories = catagory_db.getAll();
    }

}
